package bootstrap

import (
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"gopkg.in/natefinch/lumberjack.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"ttsx/server/common/global"
	"ttsx/server/model"
)

var (
	log_mode logger.LogLevel
	writer   io.Writer
)

func InitMysql() *gorm.DB {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		global.App.Config.Mysql.Name,
		global.App.Config.Mysql.Password,
		global.App.Config.Mysql.Host,
		global.App.Config.Mysql.Port,
		global.App.Config.Mysql.Database,
		global.App.Config.Mysql.Charset)

	mysqlConfig := mysql.Config{
		DSN:                       dsn,
		DefaultStringSize:         191,   // string 类型字段的默认长度
		DisableDatetimePrecision:  true,  // 禁用 datetime 精度，MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex:    true,  // 重命名索引时采用删除并新建的方式，MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn:   true,  // 用 `change` 重命名列，MySQL 8 之前的数据库和 MariaDB 不支持重命名列
		SkipInitializeWithVersion: false, // 根据版本自动配置
	}

	db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{
		Logger:                                   sqlLog(),
		DisableForeignKeyConstraintWhenMigrating: true,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
			TablePrefix:   "tb_",
		},
	})
	if err != nil {
		global.App.Log.Sugar().Errorf("mysql数据库连接失败: %s", err.Error())
		return nil
	}
	// 迁移表
	createTable(db)
	return db
}

func sqlLog() logger.Interface {

	//设置日志等级
	setSqlLogLevel()

	// 设置loggerWrite
	if global.App.Config.Mysql.EnableFileLogWriter {
		writer = &lumberjack.Logger{
			Filename:   global.App.Config.Log.LogsPath + "/" + global.App.Config.Mysql.LogFilename,
			MaxBackups: global.App.Config.Log.MaxBackups,
			MaxSize:    global.App.Config.Log.MaxSize,
			MaxAge:     global.App.Config.Log.MaxAge,
			Compress:   global.App.Config.Log.Compress,
		}
	} else {
		writer = os.Stdout
	}
	logWriter := log.New(writer, "\r\n", log.LstdFlags)

	return logger.New(logWriter, logger.Config{
		SlowThreshold:             time.Millisecond * 200,
		LogLevel:                  log_mode,
		IgnoreRecordNotFoundError: false,
		Colorful:                  !global.App.Config.Mysql.EnableFileLogWriter,
	})

}

func setSqlLogLevel() {
	switch global.App.Config.Mysql.LogMode {
	case "silent":
		log_mode = logger.Silent
	case "error":
		log_mode = logger.Error
	case "warn":
		log_mode = logger.Warn
	case "info":
		log_mode = logger.Info
	default:
		log_mode = logger.Info
	}
}

func createTable(db *gorm.DB) {
	err := db.AutoMigrate(
		&model.User{},
		&model.Address{},
		&model.GoodsSKU{},
		&model.GoodsSPU{},
		&model.GoodsType{},
		&model.GoodsImage{},
		&model.OrderGoods{},
		&model.OrderInfo{},
		&model.IndexGoodsLoop{},
		&model.IndexGoodsPromo{},
		&model.IndexGoodsType{},
	)
	if err != nil {
		global.App.Log.Sugar().Errorf("创建表失败:%s \n", err.Error())
		os.Exit(0)
	}

}
